from fastapi import APIRouter, Query, Path
from fastapiApp.controllers.map_control import map_node_controller, map_edge_controller
from fastapiApp.schemas.map_scheams import MapNodeCreate, MapNodeUpdate, MapEdgeCreate
from fastapiApp.schemas.base_scheams import Success, SuccessExtra, Fail

# 创建站点API路由器
router = APIRouter()


@router.get("/page", summary="获取站点列表")
async def get_station_list(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=1000, description="每页数量")
):
    """
    获取站点列表，支持分页
    """
    total, data = await map_node_controller.list(page=page, page_size=page_size)
    return SuccessExtra(msg='获取分页站点列表成功', data=data, total=total, page=page, page_size=page_size)


@router.get("/all", summary="获取所有站点")
async def get_all_stations():
    """
    获取所有站点信息，用于地图显示
    """
    query = await map_node_controller.model.filter(type__in=["charging", "inbound", "outbound", "sorting", "maintenance"])
    data_list = [await data.to_dict() for data in query]
    return Success(msg="获取所有站点成功", data=data_list)


@router.get("/all/node", summary="获取所有节点")
async def get_all_node():
    """
    获取所有节点信息，用于地图显示
    """
    query = await map_node_controller.model.all().values_list("id", "x", "y")
    data_list = [{"id": id, "x": x, "y": y} for id, x, y in query]
    return Success(msg="获取所有节点成功", data=data_list)


@router.post("/create", summary="添加新站点")
async def create_station(obj_in: MapNodeCreate):
    """
    添加新站点
    - **name**: 站点名称
    - **type**: 站点类型（如工作站、充电站等）
    - **x**: X坐标百分比位置（0-100）* 100
    - **y**: Y坐标百分比位置（0-100）* 100
    - **description**: 站点描述（可选）
    """
    await map_node_controller.is_exist(obj_in=obj_in)
    await map_node_controller.model.create(** obj_in.model_dump())
    return Success(msg="Created Successfully")


@router.delete("/delete/{id}", summary="删除站点")
async def delete_station(id: int = Path(..., ge=0, description="ID")):
    """
    根据ID删除站点
    """
    obj = await map_node_controller.model.get_or_none(id=id)
    if obj:
        await obj.delete()
        return Success(msg=f"Deleted Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")


@router.get("/detail/{id}", summary="获取站点详情")
async def get_station_detail(id: int = Path(..., ge=0, description="站点ID")):
    """
    根据ID获取站点详情
    """
    obj = await map_node_controller.model.get_or_none(id=id)
    if obj:
        data = await obj.to_dict()
        return Success(msg="Success", data=data)
    else:
        return Fail(msg=f"ID {id} 不存在")


@router.put("/update", summary="更新站点信息")
async def update_station(obj_in: MapNodeUpdate):
    """
    更新站点信息
    - **id**: 站点ID
    - **name**: 站点名称
    - **type**: 站点类型
    - **x**: X坐标百分比位置
    - **y**: Y坐标百分比位置
    - **description**: 站点描述
    """
    await map_node_controller.update(obj_in)
    return Success(msg=f"Update Successfully By ID = {obj_in.id}")


@router.get("/namelist", summary="获取站点名称列表")
async def get_station_name_list():
    """
    获取站点名称列表
    """
    query = await map_node_controller.model.filter(type__in=["charging", "inbound", "outbound", "sorting", "maintenance"]).values_list("id","name")
    if query:
        return Success(msg="Success", data=list(query))
    else:
        return Fail(msg="名称列表为空")

@router.get("/node/namelist", summary="获取节点名称列表")
async def get_node_name_list():
    """
    获取节点名称列表
    """
    query = await map_node_controller.model.all().values_list("id","name")
    if query:
        return Success(msg="Success", data=list(query))
    else:
        return Fail(msg="名称列表为空")

@router.post("/edge/create", summary="创建地图边")
async def create_edge(obj_in: MapEdgeCreate):
    """创建地图边"""
    # await map_edge_controller.is_exist(obj_in=obj_in)
    # 转换输入数据为字典
    data = obj_in.model_dump()

    edge_data = {
        "node_from_id": data.get("node_from"),
        "node_to_id": data.get("node_to"),
        "distance": data["distance"],
        "description": data["description"],
        "weight": data["weight"],
        "occupied": data["occupied"],
    }

    await map_edge_controller.model.create(**edge_data)
    return Success(msg="Created Successfully")


@router.get("/edge/line_list", summary="获取地图边线路列表")
async def get_edge_line_list():
    """
    获取地图边线路列表
    """
    # 使用prefetch_related预加载关联的节点数据，避免N+1查询问题
    query = await map_edge_controller.model.all().prefetch_related('node_from', 'node_to')
    data_list = []
    if query:
        for item in query:
            return_item = {}
            # 直接访问模型属性，而不是使用get方法
            return_item["id"] = item.id
            return_item["distance"] = item.distance
            return_item["weight"] = item.weight
            return_item["occupied"] = item.occupied
            return_item["start_x"] = item.node_from.x
            return_item["start_y"] = item.node_from.y
            return_item["end_x"] = item.node_to.x
            return_item["end_y"] = item.node_to.y
            data_list.append(return_item)
        return Success(msg="Success", data=data_list)
    else:
        return Fail(msg="线路列表为空")

@router.get("/edge/list", summary="获取地图边列表")
async def get_edge_list():
    """
    获取地图边列表
    """
    query = await map_edge_controller.model.all()
    data_list = [await data.to_dict() for data in query]
    if data_list:
        return Success(msg="Success", data=data_list)
    else:
        return Fail(msg="边列表为空")

@router.delete("/edge/delete/{id}", summary="删除地图边")
async def delete_edge(id: int = Path(..., ge=0, description="ID")):
    """
    根据ID删除地图边
    """
    obj = await map_edge_controller.model.get_or_none(id=id)
    if obj:
        await obj.delete()
        return Success(msg=f"Deleted Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")
